package com.training.admin.web.controller.report;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.training.admin.entity.course.Course;
import com.training.admin.entity.principal.Principal;
import com.training.admin.entity.project.ProjectPhaseCourse;
import com.training.admin.entity.project.TrainingSurveyResult;
import com.training.admin.entity.report.TrainerCourseReport;
import com.training.admin.entity.search.TrainerAppraisalReportSearch;
import com.training.admin.entity.security.Login;
import com.training.admin.service.PrincipalService;
import com.training.admin.service.ReportService;
import com.training.admin.service.TrainingSurveyResultService;
import com.training.admin.web.controller.view.ExcelTemplateView;
/**
 * 
 * @author sjh
 *
 */
@Controller
@RequestMapping("")
@MenuSetting("menu-report")
public class TrainerAppraisalResultsController {
	
	private static final Logger logger = LoggerFactory.getLogger(TrainerReportController.class);
	@Autowired
	private PrincipalService principalService;

	@Autowired
	private ReportService reportService;
	@Autowired
	private TrainingSurveyResultService trainingSurveyResultService;


	/**
	 * 讲师评估表
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/trainer-appraisal-results", method = RequestMethod.GET, params = "filter")
	@MenuSetting("submenu-trainer-appraisal-result")
	@SuppressWarnings("rawtypes")
	public ModelAndView onTrainerAppraisalReportSearch(TrainerAppraisalReportSearch trainerAppraisalReportSearch,
			Page page, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("report/trainer-appraisal-report");

		Login login = (Login) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Principal principal = principalService.loadByEmail(login.getEmail());
		if (principal.getAuthority().equals("ROLE_SUPER_USER")) {
			// 系统管理员
			// do nothing
		} else if (principal.getAuthority().equals("ROLE_DEPARTMENT_USER")) {
			// 事业部负责人
			trainerAppraisalReportSearch.setDepartmentId(principal.getDepartmentId());
		}

		int totals = reportService.count(trainerAppraisalReportSearch);
		if (totals > 0) {

			List courseList = reportService.search(trainerAppraisalReportSearch, page.with(totals));
			List<TrainerCourseReport> trainerCourseReportList = new ArrayList<TrainerCourseReport>();
			
			TrainerCourseReport trainerCourseReport = new TrainerCourseReport();
			List<TrainerCourseReport> trainerCourseReports = new ArrayList<TrainerCourseReport>();
			for (int i = 0; i < courseList.size(); i++) {
				ProjectPhaseCourse projectPhaseCourse = (ProjectPhaseCourse) courseList.get(i);
				Course course = projectPhaseCourse.getCourse();
				// set survey result / suggestion to each course
				List<TrainingSurveyResult> trainingSurveyResultList = trainingSurveyResultService
						.listByProjectPhaseCourse(projectPhaseCourse.getId());
				//管理类课程分类统计用
				// 需求匹配度
				int xu=0;
				int cntXu=0;
				// 展示技巧
				int zsjqs=0;
				int cntZsjqs=0;
				// 改进建议
				String gjjys="";
				// 内容理解深度
				int ljsds=0;
				int cntLjsds=0;
				// 讲师总体评分
				int zf=0;
				int cntDefault=0;
				for (int j=0; j<trainingSurveyResultList.size();j++){
					TrainingSurveyResult tsr = trainingSurveyResultList.get(j);
					String inputVal = tsr.getInputValue();
					if(inputVal==null || inputVal.trim().length()<1){
						//empty input continue to next
						continue;
					}

					if (tsr.getKeywords()!=null){
						//check keywords
						if( tsr.getKeywords().contains("需求匹配")){
							if(!"NA".equals(inputVal)){
			                	//int score
			                	try{
			                		xu+=Integer.valueOf(inputVal);
			                		cntXu++;
			                	}catch(Exception e){
			                		e.printStackTrace();
			                		logger.error(e.getMessage());
			                	}
			                }
						}else if( tsr.getKeywords().contains("展示技巧")){
							if(!"NA".equals(inputVal)){
			                	//int score
			                	try{
			                		zsjqs+=Integer.valueOf(inputVal);
			                		cntZsjqs++;
			                	}catch(Exception e){
			                		e.printStackTrace();
			                		logger.error(e.getMessage());
			                	}
			                }							
						}else if( tsr.getKeywords().contains("内容理解深度")){
							if(!"NA".equals(inputVal)){
			                	//int score
			                	try{
			                		ljsds+=Integer.valueOf(inputVal);
			                		cntLjsds++;
			                	}catch(Exception e){
			                		e.printStackTrace();
			                		logger.error(e.getMessage());
			                	}
			                }							
						}else if( tsr.getKeywords().contains("改进建议")){
							if(inputVal!=null && inputVal.length()>0){
								if (gjjys!=null && gjjys.length()>0){
									gjjys+=";" ;
								}
								gjjys+= inputVal;
							}
						}

					}else{
						// check key words in question body
						
						if( tsr.getQuestion().contains("主题课程是否满足您的期望")){
							//需求匹配度
							if(!"NA".equals(inputVal)){
			                	//int score
			                	try{
			                		xu+=Integer.valueOf(inputVal);
			                		cntXu++;
			                	}catch(Exception e){
			                		e.printStackTrace();
			                		logger.error(e.getMessage());
			                	}
			                }
						}else if( tsr.getQuestion().contains("授课逻辑清晰易懂，呈现演绎生动有趣")){
							//展示技巧
							if(!"NA".equals(inputVal)){
			                	//int score
			                	try{
			                		zsjqs+=Integer.valueOf(inputVal);
			                		cntZsjqs++;
			                	}catch(Exception e){
			                		e.printStackTrace();
			                		logger.error(e.getMessage());
			                	}
			                }							
						}else if( tsr.getQuestion().contains("对主题内容有深度的理解")){
							//内容理解深度
							if(!"NA".equals(inputVal)){
			                	//int score
			                	try{
			                		ljsds+=Integer.valueOf(inputVal);
			                		cntLjsds++;
			                	}catch(Exception e){
			                		e.printStackTrace();
			                		logger.error(e.getMessage());
			                	}
			                }							
						}else if( tsr.getQuestion().contains("主题课程有哪些需要改进的地方")){
							//改进建议
							if(inputVal!=null && inputVal.length()>0){
								if (gjjys!=null && gjjys.length()>0){
									gjjys+=";" ;
								}
								gjjys+= inputVal;
							}
						}else{
							//如果是评分值，计入总分，否则当成建议
							try{
								zf+=Integer.valueOf(inputVal);
								cntDefault++;
							}catch(Exception e){
								//not int value process as String
								if(inputVal!=null && inputVal.length()>0){
									if (gjjys!=null && gjjys.length()>0){
										gjjys+=";" ;
									}
									gjjys+= inputVal;
								}
							}
						}
					}
				}
				//需求平均分
				if(xu==0 || cntXu==0){
					trainerCourseReport.setPiPeiDu("0");
				}else{
				    BigDecimal bd=new BigDecimal(xu*1.0/cntXu);
			        double d1=bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
					trainerCourseReport.setPiPeiDu(""+ String.valueOf(d1));
				}
				// 展示技巧
				if(zsjqs==0 || cntZsjqs==0){
					trainerCourseReport.setZsjq("0");
				}else{
				    BigDecimal bd=new BigDecimal(zsjqs*1.0/cntZsjqs);
                    double d1=bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
					trainerCourseReport.setZsjq(""+ String.valueOf(d1));
				}
				// 内容理解深度
				if(ljsds==0 || cntLjsds==0){
					trainerCourseReport.setLjsd("0");
				}else{
				    BigDecimal bd=new BigDecimal(ljsds*1.0/cntLjsds);
                    double d1=bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
					trainerCourseReport.setLjsd(""+ String.valueOf(d1));
				}
                // 改进建议
				trainerCourseReport.setGjjy(gjjys);
				// 总体评分
				zf+=xu+zsjqs+ljsds;
				cntDefault+=cntXu+cntZsjqs+cntLjsds;
				
				if(zf==0 || cntDefault==0){
					trainerCourseReport.setZf("0");
				}else{
				    BigDecimal bd=new BigDecimal(zf*1.0/cntDefault);
		            double d1=bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
					trainerCourseReport.setZf(""+ String.valueOf(d1));
				}
				
				//讲师评分  =展示技巧 + 理解深度
				if((zsjqs+ljsds)==0 || (cntZsjqs+cntLjsds)==0){
					//如果空值， 用总分代替
					trainerCourseReport.setTrainerSurveyResult(trainerCourseReport.getZf());
				}else{
				    BigDecimal bd=new BigDecimal((zsjqs+ljsds) *1.0 /(cntZsjqs+cntLjsds));
                    double d1=bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
					trainerCourseReport.setTrainerSurveyResult(""+ String.valueOf(d1));
				}
				
				//课程评分（  =总分）
				trainerCourseReport.setCourseSurveyResult(trainerCourseReport.getZf());
				

				trainerCourseReports.add(new TrainerCourseReport(trainerCourseReport));

				projectPhaseCourse.setCourse(course);
				trainerCourseReportList.add(new TrainerCourseReport(projectPhaseCourse, trainerCourseReports.get(i)));
			}

			modelAndView.addObject("courses", trainerCourseReportList);
			modelAndView.addObject("recordCount", trainerCourseReportList.size());
			modelAndView.addObject("page", page);

		}

		modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));

		return modelAndView;
	}
	
	/**
	 * 讲师评估结果表 - 导出
	 * 
	 * @param search
	 * @return
	 */
	@RequestMapping(value = "/reports/trainer-appraisal-report-export", method = RequestMethod.GET)
	@MenuSetting("submenu-trainer-appraisal-result")
	@SuppressWarnings("rawtypes")
	public ModelAndView trainerAppraisalReportExport(TrainerAppraisalReportSearch trainerAppraisalReportSearch,
			Page page) {

		ModelAndView modelAndView = new ModelAndView(
				new ExcelTemplateView("trainer-appraisal-result.xls", "trainer-appraisal-report.xls"));
		Login login = (Login) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Principal principal = principalService.loadByEmail(login.getEmail());
		if (principal.getAuthority().equals("ROLE_SUPER_USER")) {
			// 系统管理员
			// do nothing
		} else if (principal.getAuthority().equals("ROLE_DEPARTMENT_USER")) {
			// 事业部负责人
			trainerAppraisalReportSearch.setDepartmentId(principal.getDepartmentId());
		}
		

		int totals = reportService.count(trainerAppraisalReportSearch);
		if (totals > 0) {

			List courseList = reportService.searchForExport(trainerAppraisalReportSearch);

			List<TrainerCourseReport> trainerCourseReportList = new ArrayList<TrainerCourseReport>();

			TrainerCourseReport trainerCourseReport = new TrainerCourseReport();
			List<TrainerCourseReport> trainerCourseReports = new ArrayList<TrainerCourseReport>();

			for (int i = 0; i < courseList.size(); i++) {
				ProjectPhaseCourse projectPhaseCourse = (ProjectPhaseCourse) courseList.get(i);
				Course course = projectPhaseCourse.getCourse();
				// set survey result / suggestion to each course
				List<TrainingSurveyResult> trainingSurveyResultList = trainingSurveyResultService
						.listByProjectPhaseCourse(projectPhaseCourse.getId());
				//管理类课程分类统计用
				// 需求匹配度
				int xu=0;
				int cntXu=0;
				// 展示技巧
				int zsjqs=0;
				int cntZsjqs=0;
				// 改进建议
				String gjjys="";
				// 内容理解深度
				int ljsds=0;
				int cntLjsds=0;
				// 讲师总体评分
				int zf=0;
				int cntDefault=0;
				for (int j=0; j<trainingSurveyResultList.size();j++){
					TrainingSurveyResult tsr = trainingSurveyResultList.get(j);
					String inputVal = tsr.getInputValue();
					if(inputVal==null || inputVal.trim().length()<1){
						//empty input continue to next
						continue;
					}

					if (tsr.getKeywords()!=null){
						//check keywords
						if( tsr.getKeywords().contains("需求匹配")){
							if(!"NA".equals(inputVal)){
			                	//int score
			                	try{
			                		xu+=Integer.valueOf(inputVal);
			                		cntXu++;
			                	}catch(Exception e){
			                		e.printStackTrace();
			                		logger.error(e.getMessage());
			                	}
			                }
						}else if( tsr.getKeywords().contains("展示技巧")){
							if(!"NA".equals(inputVal)){
			                	//int score
			                	try{
			                		zsjqs+=Integer.valueOf(inputVal);
			                		cntZsjqs++;
			                	}catch(Exception e){
			                		e.printStackTrace();
			                		logger.error(e.getMessage());
			                	}
			                }							
						}else if( tsr.getKeywords().contains("内容理解深度")){
							if(!"NA".equals(inputVal)){
			                	//int score
			                	try{
			                		ljsds+=Integer.valueOf(inputVal);
			                		cntLjsds++;
			                	}catch(Exception e){
			                		e.printStackTrace();
			                		logger.error(e.getMessage());
			                	}
			                }							
						}else if( tsr.getKeywords().contains("改进建议")){
							if(inputVal!=null && inputVal.length()>0){
								if (gjjys!=null && gjjys.length()>0){
									gjjys+=";" ;
								}
								gjjys+= inputVal;
							}
						}

					}else{
						// check key words in question body
						
						if( tsr.getQuestion().contains("主题课程是否满足您的期望")){
							//需求匹配度
							if(!"NA".equals(inputVal)){
			                	//int score
			                	try{
			                		xu+=Integer.valueOf(inputVal);
			                		cntXu++;
			                	}catch(Exception e){
			                		e.printStackTrace();
			                		logger.error(e.getMessage());
			                	}
			                }
						}else if( tsr.getQuestion().contains("授课逻辑清晰易懂，呈现演绎生动有趣")){
							//展示技巧
							if(!"NA".equals(inputVal)){
			                	//int score
			                	try{
			                		zsjqs+=Integer.valueOf(inputVal);
			                		cntZsjqs++;
			                	}catch(Exception e){
			                		e.printStackTrace();
			                		logger.error(e.getMessage());
			                	}
			                }							
						}else if( tsr.getQuestion().contains("对主题内容有深度的理解")){
							//内容理解深度
							if(!"NA".equals(inputVal)){
			                	//int score
			                	try{
			                		ljsds+=Integer.valueOf(inputVal);
			                		cntLjsds++;
			                	}catch(Exception e){
			                		e.printStackTrace();
			                		logger.error(e.getMessage());
			                	}
			                }							
						}else if( tsr.getQuestion().contains("主题课程有哪些需要改进的地方")){
							//改进建议
							if(inputVal!=null && inputVal.length()>0){
								if (gjjys!=null && gjjys.length()>0){
									gjjys+=";" ;
								}
								gjjys+= inputVal;
							}
						}else{
							//如果是评分值，计入总分，否则当成建议
							try{
								zf+=Integer.valueOf(inputVal);
								cntDefault++;
							}catch(Exception e){
								//not int value process as String
								if(inputVal!=null && inputVal.length()>0){
									if (gjjys!=null && gjjys.length()>0){
										gjjys+=";" ;
									}
									gjjys+= inputVal;
								}
							}
						}
					}
				}
				//需求平均分
				if(xu==0 || cntXu==0){
					trainerCourseReport.setPiPeiDu("0");
				}else{
				    BigDecimal bd=new BigDecimal((xu*1.0/cntXu));
                    double d1=bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
					trainerCourseReport.setPiPeiDu(""+ String.valueOf(d1));
				}
				// 展示技巧
				if(zsjqs==0 || cntZsjqs==0){
					trainerCourseReport.setZsjq("0");
				}else{
				    BigDecimal bd=new BigDecimal((zsjqs*1.0/cntZsjqs));
                    double d1=bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
					trainerCourseReport.setZsjq(""+ String.valueOf(d1));
				}
				// 内容理解深度
				if(ljsds==0 || cntLjsds==0){
					trainerCourseReport.setLjsd("0");
				}else{
				    BigDecimal bd=new BigDecimal((ljsds*1.0/cntLjsds));
                    double d1=bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
					trainerCourseReport.setLjsd(""+ String.valueOf(d1));
				}
                // 改进建议
				trainerCourseReport.setGjjy(gjjys);
				// 总体评分
				zf+=xu+zsjqs+ljsds;
				cntDefault+=cntXu+cntZsjqs+cntLjsds;
				
				if(zf==0 || cntDefault==0){
					trainerCourseReport.setZf("0");
				}else{
				    BigDecimal bd=new BigDecimal(zf*1.0/cntDefault);
		            double d1=bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
					trainerCourseReport.setZf(""+ String.valueOf(d1));
				}
				
				//讲师评分  =展示技巧 + 理解深度
				if((zsjqs+ljsds)==0 || (cntZsjqs+cntLjsds)==0){
					//如果空值， 用总分代替
					trainerCourseReport.setTrainerSurveyResult(trainerCourseReport.getZf());
				}else{
				    BigDecimal bd=new BigDecimal((zsjqs+ljsds) *1.0 /(cntZsjqs+cntLjsds));
                    double d1=bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
					trainerCourseReport.setTrainerSurveyResult(""+ String.valueOf(d1));
				}
				
				//课程评分（  =总分）
				trainerCourseReport.setCourseSurveyResult(trainerCourseReport.getZf());
				

				trainerCourseReports.add(new TrainerCourseReport(trainerCourseReport));

				projectPhaseCourse.setCourse(course);
				trainerCourseReportList.add(new TrainerCourseReport(projectPhaseCourse, trainerCourseReports.get(i)));
			}
			modelAndView.addObject("results", trainerCourseReportList);

		}
		return modelAndView;

	}
}
